package admin.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.DealModel;
import models.ProductModel;
import admin.data.DealData;
import admin.data.IdCountData;
import admin.forms.DealForm;
import data.CountData;

@SuppressWarnings("serial")
public class AddDealServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(AddDealServlet.class
			.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		try {
			HttpSession ss = request.getSession();
			ss.setAttribute("action", "add");
			request.getRequestDispatcher("/admin/pages/form_deal.jsp").forward(
					request, response);
		} catch (ServletException e) {
			System.out.println("Error when redirect add deal page !");
			log.warning("Error when redirect add deal page !");
			log.warning(e.toString());
			e.printStackTrace();
		}
	}

	@SuppressWarnings({ "rawtypes" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		DealModel deal = new DealModel();
		TreeMap check = new TreeMap();
		List<ProductModel> listProduct = new ArrayList<ProductModel>();
		new DealForm().checkValid(request, check, deal, listProduct);
		HttpSession session = request.getSession();
		session.setAttribute("action", "add");
		if (check.size() != 0) {
			session.setAttribute("check", check);
			session.setAttribute("deal", deal);
			session.setAttribute("error",
					"Không thể thêm mới Deal do các lỗi dưới đây !");
			response.sendRedirect("/admin/deal/add");
		} else {
			if (deal.getDealType() == 1) {
				DealModel dealMarketing = DealData.getDealMarketing(
						deal.getCity(), deal.getCategory());
				if (dealMarketing != null&&dealMarketing.getDealId().length()>0) {
					dealMarketing.setDealType(0);
					dealMarketing.setDateToOrder(Calendar.getInstance().getTime());
					DealData.insert(dealMarketing);
				}	
				deal.setDateToOrder(Calendar.getInstance().getTime());
			}
			deal.setDoc(Calendar.getInstance().getTime());
			deal.setDealId(IdCountData.getIdByType("1"));
			DealData.insert(deal, listProduct);
			CountData countData = new CountData();
			countData.recountAll();
			session.setAttribute("success", "Thêm mới deal thành công !");
			response.sendRedirect("/admin/deal/add");
		}
	}
}
